const express = require('express')
const Router = express.Router()
const sql  =require('./sql/sql')
const {success,fail} = require('./utils/send')
const captcha = require("svg-captcha");
const decode = require('./token/token')
const tools = require('./utils/syntax')


//验证码
Router.get('/validate', (req, res) => {
    res.header('Access-Control-Allow-Origin', "*");
    const cap = captcha.create({
        size: 4,
        ignoreChars: '0o1il',
        noise: 1,
        color: true,
        background: '#cc9966'
    });
    req.session.captcha = cap.text; // session 存储
    res.type('svg'); // 响应的类型
    res.send(cap.data);
});



//购物车选中状态
Router.get('/shopCheck/:skuId/:isChecked',async (req,res)=>{
     let {skuId,isChecked} = req.params
     let uuid = req.headers.tempid
     
     //UPDATE `ego`.`nideshop_shopcart` SET `isChecked` = 0 WHERE `id` = 40
     let syntax = "update nideshop_shopcart SET ischecked=? where uuid=? and skuid=?"
     let result = await sql(syntax,[isChecked,uuid,skuId])
    //  let result = await sql(`update nideshop_shopcart set ischecked="${isChecked}" where uuid="${uuid}" and skuid=${skuId}`)
     if(result.affectedRows > 0){
         success(res,[],'修改成功')
     }else{
         fail(res,[],'勾选失败')
     }
})

//删除购物车单个商品
Router.delete('/delsection/:skuId',async (req,res)=>{
    let uuid = req.headers.tempid
    let {skuId} = req.params
    // console.log(uuid,skuId);
    let syntax = "DELETE FROM nideshop_shopcart where uuid=? and skuid=?"
    let result = await sql(syntax,[uuid,skuId])
    if(result.affectedRows > 0){
        success(res,[],'删除商品成功')
    }else{
        fail(res,[],'删除商品失败')
    }
})

// 注册账号
Router.post('/register',async (req,res)=>{
    let {mobile,password} = req.body.params

    // 判断数据是否存在
    let some  = "select * from nideshop_account where mobile=?"
    let checkSome = await sql(some,mobile)
    if(checkSome.length > 0){
        return fail(res,[],'用户手机已存在')
    }


    let syntax = "insert into nideshop_account(mobile,password) value(?,?)"
    // let syntax = "insert into nideshop_account set mobile='123456' and password='123456'"
    let result = await sql(syntax,[mobile,password])
    // let result = await sql(syntax)
    if(result.affectedRows > 0){
        // 加密
        let token =  decode.sign(mobile)
        result.token = token
        success(res,result,'注册成功')
    }else{
        fail(res,[],'注册失败')
    }
})

//登录
Router.post('/account',async (req,res)=>{
    let {username,password} = req.body
    let mobile = username
    let syntax  ="select * from nideshop_account where mobile=? and password=?"
    let result = await sql(syntax,[mobile,password])

    let token =  decode.sign({mobile,password}).split('Bearer ')[1]
    
    if(result.length > 0){
        // success(res,['username'+ result[0].username||result[0].mobile,token],'登陆成功')
        success(res,{ username:result[0].username||result[0].mobile,token},'登陆成功')
    }else{
        fail(res,[],'账号或者密码错误')
    }
})

// 有token,获取用户信息
Router.get('/authorizetion',async (req,res)=>{
    let {token} = req.headers 
    if(token){

        let {mobile,password} = decode.decode('Bearer ' +token)
        let syntax  ="select * from nideshop_account where mobile=? and password=?"
        let result = await sql(syntax,[mobile,password])
        let newToken =  decode.sign({mobile,password}).split('Bearer ')[1]
        
        if(result.length > 0){
            // success(res,['username'+ result[0].username||result[0].mobile,token],'登陆成功')
            success(res,{ username:result[0].username||result[0].mobile,token:newToken},'登陆成功')
        }else{
            fail(res,[],'账号或者密码错误')
        }
    }else{
        fail(res,[],'token过期')
    }

})

//收货地址
Router.get('/address',async (req,res)=>{
    let {token} = req.headers
    
    if(token){
        let result = await decode.getAccount(token,sql)
        // let result =await sql(tools('selectAcctount'),[mobile,password])
        let address = await sql(tools('address'),result[0].id)
        // 数组中长度2 
        // [
        //     RowDataPacket {
        //       id: 3,
        //       name: '小明',
        //       user_id: 14,
        //       country_id: 1,
        //       province_id: 20,
        //       city_id: 233,
        //       district_id: 2414,
        //       address: '民族大道1号',
        //       mobile: '13800008888',
        //       is_default: 1
        //     },
        //     RowDataPacket {
        //       id: 4,
        //       name: 'liz',
        //       user_id: 14,
        //       country_id: 1,
        //       province_id: 20,
        //       city_id: 233,
        //       district_id: 2413,
        //       address: '龙洞2号',
        //       mobile: '13888888888',
        //       is_default: 0
        //     }
        //   ]
        let pList = []
        address.forEach( (item,index)=>{
            let {country_id,province_id,city_id,district_id} = item
            let syntax = "select * from nideshop_region where id=? and type=0 ; select * from nideshop_region where id=? and type=1 ;select * from nideshop_region where id=? and type=2; select * from nideshop_region where id=? and type=3 ";
            let params  = [country_id,province_id,city_id,district_id]
            let detail = sql(syntax,params)
            pList.push(detail)
         })
            let waitList = await Promise.all(pList)
             waitList.forEach( (item,index) => {
                address[index].detailAddress = ''
                        item.forEach((citem,cindex)=>{
                            address[index].detailAddress += citem[0].name
                        })
            })
        success(res,[address],'获取地址成功',[])
    }else{
        fail(res,[],'token过期')
    }
})

// 有TOKEN获取UUID与用户名购物车
Router.get('/bothCart',async(req,res)=>{
    let {token,tempid} = req.headers
    var list = []
    var totalbuy=0,allPrice=0;
    var idCart,uuCart,total,price;
    if(!token && !tempid){
         fail(res,[uuCart,totalbuy,allPrice],'token过期')
         
    }else{
        let promiseList = []  //异步处理列表
        if(token){
            let result = await decode.getAccount(token,sql)
            idCart = await sql(tools('userCart'),result[0].id)
            let skuid = idCart.map((item)=> item.skuid)
        }
        if(tempid){
            uuCart = await sql(tools('uuCart'),tempid)
             uuCart.map( (item,index)=> {
                let skuid = item.skuid
                // let element =await sql(tools('selectGoods'),skuid)
                let element = sql(tools('selectGoods'),skuid)
                // 服务器中计算单个商品 数量 与总价
                list.push(element)
            })
            let afPro = await Promise.all(list)
            uuCart.map((item,index) =>{
                uuCart[index].goods = afPro[index][0]
                if(item.isChecked){
                    item.price = afPro[index][0].retail_price * item.skunum
                    allPrice += item.price
                    totalbuy += item.skunum
                   
                }
              
            })
            
        }
        success(res,[{totalbuy},{allPrice},uuCart],'获取成功')
    }

    
})


module.exports = Router